<!DOCTYPE html>
<html lang="zh-Hans">
  <head>
    
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>


<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

<meta name="theme-color" content="#f8f5ec" />
<meta name="msapplication-navbutton-color" content="#f8f5ec">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="#f8f5ec">



  <meta name="description" content="语言中字符串拼接有好几种方式,从最普通的`+`拼接到`buffer`字节缓冲都有.但是如果遇到大量的字符串拼接的情况,他们之间的性能差异还是需要注意的."/>




  <meta name="keywords" content="golang, 技术, 杂鱼君的博客" />










  <link rel="alternate" href="/atom.xml" title="杂鱼君的博客">




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=2.6.0" />



<link rel="canonical" href="http://notes.wen.moe/post/go-string-implode-diff-way.html"/>


<link rel="stylesheet" type="text/css" href="/css/style.css?v=2.6.0" />



  <link rel="stylesheet" type="text/css" href="/lib/fancybox/jquery.fancybox.css" />




  



  <script id="baidu_push">
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>









    <title> go 语言中哪种字符串拼接的方式最高效? - 杂鱼君的博客 </title>
  </head>

  <body><div id="mobile-navbar" class="mobile-navbar">
  <div class="mobile-header-logo">
    <a href="/." class="logo">杂鱼君的博客</a>
  </div>
  <div class="mobile-navbar-icon">
    <span></span>
    <span></span>
    <span></span>
  </div>
</div>

<nav id="mobile-menu" class="mobile-menu slideout-menu">
  <ul class="mobile-menu-list">
    
      <a href="/">
        <li class="mobile-menu-item">
          
          
            Home
          
        </li>
      </a>
    
      <a href="/archives/">
        <li class="mobile-menu-item">
          
          
            Archives
          
        </li>
      </a>
    
      <a href="/tags">
        <li class="mobile-menu-item">
          
          
            Tags
          
        </li>
      </a>
    
      <a href="/about">
        <li class="mobile-menu-item">
          
          
            About
          
        </li>
      </a>
    
  </ul>
</nav>

    <div class="container" id="mobile-panel">
      <header id="header" class="header"><div class="logo-wrapper">
  <a href="/." class="logo">杂鱼君的博客</a>
</div>

<nav class="site-navbar">
  
    <ul id="menu" class="menu">
      
        <li class="menu-item">
          <a class="menu-item-link" href="/">
            
            
              Home
            
          </a>
        </li>
      
        <li class="menu-item">
          <a class="menu-item-link" href="/archives/">
            
            
              Archives
            
          </a>
        </li>
      
        <li class="menu-item">
          <a class="menu-item-link" href="/tags">
            
            
              Tags
            
          </a>
        </li>
      
        <li class="menu-item">
          <a class="menu-item-link" href="/about">
            
            
              About
            
          </a>
        </li>
      
    </ul>
  
</nav>

      </header>

      <main id="main" class="main">
        <div class="content-wrapper">
          <div id="content" class="content">
            
  
  <article class="post">
    <header class="post-header">
      <h1 class="post-title">
        
          go 语言中哪种字符串拼接的方式最高效?
        
      </h1>

      <div class="post-meta">
        <span class="post-time">
          2017-04-13
        </span>
        
        
      </div>
    </header>

    
    
  <div class="post-toc" id="post-toc">
    <h2 class="post-toc-title">Contents</h2>
    <div class="post-toc-content">
      <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#常用的字符串拼接方式"><span class="toc-text">常用的字符串拼接方式</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#测试代码"><span class="toc-text">测试代码</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#测试结果"><span class="toc-text">测试结果</span></a></li></ol>
    </div>
  </div>


    <div class="post-content">
      
        <h2 id="常用的字符串拼接方式"><a href="#常用的字符串拼接方式" class="headerlink" title="常用的字符串拼接方式"></a>常用的字符串拼接方式</h2><ul>
<li>直接使用<code>+=</code>操作符拼接,最简单且各种语言都通用.不过可以很自然的推测他的性能是最差的</li>
<li>把要拼接的字符串放入<code>[]string</code>切片中,然后再使用<code>strings.join()</code>方式组合成一个字符串</li>
<li>使用<code>bytes.Buffer</code>,将所有字符串写入<code>Buffer</code>变量,最后通过<code>Buffer.string()</code>方式输出</li>
<li>将字符串转换成<code>[]byte</code>字节数组,然后全部<code>append()</code>到一个大<code>[]byte</code>数组中,最后再转换成字符串</li>
</ul>
<h2 id="测试代码"><a href="#测试代码" class="headerlink" title="测试代码"></a>测试代码</h2><p>因为 go 语言自带了很好用的 benchmark 测试框架,因此我们可以写一个简单的测试用例,具体代码如下:</p>
<figure class="highlight golang"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">package</span> main</div><div class="line"></div><div class="line"><span class="keyword">import</span> (</div><div class="line">    <span class="string">"bytes"</span></div><div class="line">    <span class="string">"strings"</span></div><div class="line">    <span class="string">"testing"</span></div><div class="line">)</div><div class="line"></div><div class="line"><span class="keyword">var</span> (</div><div class="line">    strs = []<span class="keyword">string</span>&#123;</div><div class="line">        <span class="string">"one"</span>,</div><div class="line">        <span class="string">"two"</span>,</div><div class="line">        <span class="string">"three"</span>,</div><div class="line">        <span class="string">"four"</span>,</div><div class="line">        <span class="string">"five"</span>,</div><div class="line">        <span class="string">"一"</span>,</div><div class="line">        <span class="string">"二"</span>,</div><div class="line">        <span class="string">"三"</span>,</div><div class="line">        <span class="string">"四"</span>,</div><div class="line">        <span class="string">"五"</span>,</div><div class="line">    &#125;</div><div class="line">)</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">Benchmark_strConcat</span><span class="params">(b *testing.B)</span></span> &#123;</div><div class="line">    <span class="keyword">for</span> i := <span class="number">0</span>; i &lt; b.N; i++ &#123;</div><div class="line">        <span class="keyword">var</span> (</div><div class="line">            s <span class="keyword">string</span></div><div class="line">        )</div><div class="line">        <span class="keyword">for</span> _, str := <span class="keyword">range</span> strs &#123;</div><div class="line">            s += str</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">Benchmark_strJoin</span><span class="params">(b *testing.B)</span></span> &#123;</div><div class="line">    <span class="keyword">for</span> i := <span class="number">0</span>; i &lt;= b.N; i++ &#123;</div><div class="line">        strings.Join(strs, <span class="string">""</span>)</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">Benchmark_strByte</span><span class="params">(b *testing.B)</span></span> &#123;</div><div class="line">    <span class="keyword">for</span> i := <span class="number">0</span>; i &lt; b.N; i++ &#123;</div><div class="line">        <span class="keyword">var</span> (</div><div class="line">            s []<span class="keyword">byte</span></div><div class="line">        )</div><div class="line">        <span class="keyword">for</span> _, str := <span class="keyword">range</span> strs &#123;</div><div class="line">            s = <span class="built_in">append</span>(s, []<span class="keyword">byte</span>(str)...)</div><div class="line">        &#125;</div><div class="line">        _ = <span class="keyword">string</span>(s)</div><div class="line">    &#125;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">func</span> <span class="title">Benchmark_strBuff</span><span class="params">(b *testing.B)</span></span> &#123;</div><div class="line">    <span class="keyword">for</span> i := <span class="number">0</span>; i &lt; b.N; i++ &#123;</div><div class="line">        <span class="keyword">var</span> (</div><div class="line">            buf bytes.Buffer</div><div class="line">        )</div><div class="line">        <span class="keyword">for</span> _, str := <span class="keyword">range</span> strs &#123;</div><div class="line">            buf.WriteString(str)</div><div class="line">        &#125;</div><div class="line">        buf.String()</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<h2 id="测试结果"><a href="#测试结果" class="headerlink" title="测试结果"></a>测试结果</h2><p>测试结果如下</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">Benchmark_strConcat-8        3000000           663 ns/op</div><div class="line">Benchmark_strJoin-8         10000000           204 ns/op</div><div class="line">Benchmark_strByte-8          5000000           372 ns/op</div><div class="line">Benchmark_strBuff-8          5000000           271 ns/op</div><div class="line">PASS</div><div class="line">ok      <span class="built_in">test</span>/string 8.738s</div></pre></td></tr></table></figure>
<p>可见最慢的就是直接用<code>+</code>号拼接,最快的是<code>strings.join()</code>.不过<code>strings.join()</code>对数据格式有要求,组装<code>[]string</code>还需要做额外的操作. 而<code>bytes.Buffer</code>相比之下使用方便,而且附带很多有用的函数,比如<code>truncate()</code>等. 因此日常使用还是推荐<code>bytes.Buffer</code>.</p>

      
    </div>

    
      
      

  <div class="post-copyright">
    <p class="copyright-item">
      <span>Author: </span>
      <a href="http://notes.wen.moe">zakokun</a>
    </p>
    <p class="copyright-item">
      <span>Link: </span>
      <a href="http://notes.wen.moe/post/go-string-implode-diff-way.html">http://notes.wen.moe/post/go-string-implode-diff-way.html</a>
    </p>
    <p class="copyright-item">
      <span>License: </span>
      
      <a rel="license" href="http://creativecommons.org/licenses/by-nc/4.0/" target="_blank">知识共享署名-非商业性使用 4.0 国际许可协议</a>
    </p>
  </div>



      
      
    

    
      <footer class="post-footer">
        
          <div class="post-tags">
            
              <a href="/tags/golang/">golang</a>
            
              <a href="/tags/技术/">技术</a>
            
          </div>
        
        
        
  <nav class="post-nav">
    
    
      <a class="next" href="/post/build-fluent-net-env.html">
        <span class="next-text nav-default">搭建自由的网络环境</span>
        <span class="prev-text nav-mobile">Next</span>
        <i class="iconfont icon-right"></i>
      </a>
    
  </nav>

      </footer>
    

  </article>


          </div>
          
  <div class="comments" id="comments">
    
      <div id="disqus_thread">
        <noscript>
          Please enable JavaScript to view the
          <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a>
        </noscript>
      </div>
    
  </div>


        </div>
      </main>

      <footer id="footer" class="footer">

  <div class="social-links">
    
      
        
          <a href="mailto:me@wen.moe" class="iconfont icon-email" title="email"></a>
        
      
    
      
    
      
    
      
    
      
    
      
    
      
    
      
    
      
    
      
    
      
    
      
    
      
        
          <a href="https://www.instagram.com/zakokun" class="iconfont icon-instagram" title="instagram"></a>
        
      
    
    
    
  </div>


<div class="copyright">
  <span class="power-by">
    Powered by <a class="hexo-link" href="https://hexo.io/">Hexo</a>
  </span>
  <span class="division">|</span>
  <span class="theme-info">
    Theme -
    <a class="theme-link" href="https://github.com/ahonn/hexo-theme-even">Even</a>
  </span>
  <span class="division">|</span>
  <span class="theme-info">
    Hosted by <a class="theme-link" href="https://pages.coding.me" style="font-weight: bold">Coding Pages</a>
  </span>

  <span class="copyright-year">
    
    &copy;
    
      2014 -
    
    2017

    <span class="heart">
      <i class="iconfont icon-heart"></i>
    </span>
    <span class="author">zakokun</span>
  </span>
</div>

      </footer>

      <div class="back-to-top" id="back-to-top">
        <i class="iconfont icon-up"></i>
      </div>
    </div>

    
  
  <script type="text/javascript">
    var disqus_config = function () {
        this.page.url = 'http://notes.wen.moe/post/go-string-implode-diff-way.html';
        this.page.identifier = 'post/go-string-implode-diff-way.html';
        this.page.title = 'go 语言中哪种字符串拼接的方式最高效?';
    };
    (function() {
    var d = document, s = d.createElement('script');

    s.src = '//evanszhang.disqus.com/embed.js';

    s.setAttribute('data-timestamp', +new Date());
    (d.head || d.body).appendChild(s);
    })();  
  </script>




    
  





  
    <script type="text/javascript" src="/lib/jquery/jquery-3.1.1.min.js"></script>
  

  
    <script type="text/javascript" src="/lib/slideout/slideout.js"></script>
  

  
    <script type="text/javascript" src="/lib/fancybox/jquery.fancybox.pack.js"></script>
  


    <script type="text/javascript" src="/js/src/even.js?v=2.6.0"></script>
<script type="text/javascript" src="/js/src/bootstrap.js?v=2.6.0"></script>

  </body>
</html>
